package com.scau.RBAC.dao.impl;

import com.scau.RBAC.dao.UserRoleDao;
import com.scau.RBAC.model.entity.UserRole;
import com.scau.RBAC.util.DBConnectionPool;
import com.scau.RBAC.util.DatabaseException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * PostgreSQL数据库的UserRoleDao实现
 */
public class PostgreSqlUserRoleDao implements UserRoleDao {
    private final QueryRunner queryRunner;

    public PostgreSqlUserRoleDao() {
        DataSource dataSource = DBConnectionPool.getDataSource();
        this.queryRunner = new QueryRunner(dataSource);
    }

    @Override
    public int insert(UserRole entity) {
        try {
            return queryRunner.update(
                    "INSERT INTO user_roles(user_id, role_id, created_time, created_by) VALUES(?, ?, ?, ?)",
                    entity.getUserId(), entity.getRoleId(), entity.getCreatedTime(), entity.getCreatedBy()
            );
        } catch (SQLException e) {
            throw new DatabaseException("插入用户角色关联失败", e);
        }
    }

    @Override
    public int batchInsert(List<UserRole> entities) {
        try {
            Object[][] params = new Object[entities.size()][4];
            for (int i = 0; i < entities.size(); i++) {
                UserRole userRole = entities.get(i);
                params[i][0] = userRole.getUserId();
                params[i][1] = userRole.getRoleId();
                params[i][2] = userRole.getCreatedTime();
                params[i][3] = userRole.getCreatedBy();
            }

            int[] results = queryRunner.batch(
                    "INSERT INTO user_roles(user_id, role_id, created_time, created_by) VALUES(?, ?, ?, ?)",
                    params
            );

            int total = 0;
            for (int result : results) {
                total += result;
            }
            return total;
        } catch (SQLException e) {
            throw new DatabaseException("批量插入用户角色关联失败", e);
        }
    }

    @Override
    public int deleteById(Long id) {
        // UserRole没有单独的ID字段，使用userId和roleId作为联合主键
        // 这里简单返回0，表示不支持通过单一ID删除
        return 0;
    }

    @Override
    public int batchDelete(List<Long> ids) {
        // 不支持通过单一ID批量删除
        return 0;
    }

    @Override
    public int update(UserRole entity) {
        // UserRole通常不需要更新操作，这里简单返回0
        return 0;
    }

    @Override
    public UserRole findById(Long id) {
        // UserRole没有单独的ID字段，使用userId和roleId作为联合主键
        return null;
    }

    @Override
    public List<UserRole> findAll() {
        try {
            return queryRunner.query("SELECT * FROM user_roles", new BeanListHandler<>(UserRole.class));
        } catch (SQLException e) {
            throw new DatabaseException("查询所有用户角色关联失败", e);
        }
    }

    @Override
    public List<UserRole> findByPage(Map<String, Object> params, int pageNum, int pageSize) {
        try {
            StringBuilder sql = new StringBuilder("SELECT * FROM user_roles WHERE 1=1");
            Object[] queryParams = buildQueryParams(sql, params);

            sql.append(" LIMIT ? OFFSET ?");
            Object[] finalParams = new Object[queryParams.length + 2];
            System.arraycopy(queryParams, 0, finalParams, 0, queryParams.length);
            finalParams[queryParams.length] = pageSize;
            finalParams[queryParams.length + 1] = (pageNum - 1) * pageSize;

            return queryRunner.query(sql.toString(), new BeanListHandler<>(UserRole.class), finalParams);
        } catch (SQLException e) {
            throw new DatabaseException("分页查询用户角色关联失败", e);
        }
    }

    @Override
    public long count(Map<String, Object> params) {
        try {
            StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM user_roles WHERE 1=1");
            Object[] queryParams = buildQueryParams(sql, params);

            return queryRunner.query(sql.toString(), rs -> {
                if (rs.next()) {
                    return rs.getLong(1);
                }
                return 0L;
            }, queryParams);
        } catch (SQLException e) {
            throw new DatabaseException("统计用户角色关联数量失败", e);
        }
    }

    @Override
    public int deleteByUserId(Long userId) {
        try {
            return queryRunner.update("DELETE FROM user_roles WHERE user_id = ?", userId);
        } catch (SQLException e) {
            throw new DatabaseException("根据用户ID删除用户角色关联失败", e);
        }
    }

    @Override
    public int deleteByRoleId(Long roleId) {
        try {
            return queryRunner.update("DELETE FROM user_roles WHERE role_id = ?", roleId);
        } catch (SQLException e) {
            throw new DatabaseException("根据角色ID删除用户角色关联失败", e);
        }
    }

    private Object[] buildQueryParams(StringBuilder sql, Map<String, Object> params) {
        // 简化实现
        return new Object[0];
    }
}